package com.oocl.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.oocl.dao.FavcDao;
import com.oocl.pojo.Favc;
import com.oocl.util.DBUtil;

public class FavcDaoImpl implements FavcDao{

	public List<Favc> findAll() {
		String sql = "select * from favc";
		List<Favc> list = new ArrayList<Favc>();
		Connection con = null;
		PreparedStatement stat =null;
		ResultSet rs = null;
        try {
        	con = DBUtil.createConnection();
			stat = con.prepareStatement(sql);
			rs = stat.executeQuery();
			while(rs.next()){
				Favc f = new Favc();
				f.setId(rs.getInt("id"));
				f.setFavcName(rs.getString("favcname"));
				list.add(f);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(con, stat, rs);
			
		}
		return list;
	}

	public List<Favc> findFavcByCId(Integer id) {
		// TODO Auto-generated method stub
		String sql = "select * from favc f,customer_favc cf where f.id= cf.favc_id and cf.customer_id=?";
		List<Favc> list = new ArrayList<Favc>();
		Connection con = null;
		PreparedStatement stat =null;
		ResultSet rs = null;
        try {
        	con = DBUtil.createConnection();
			stat = con.prepareStatement(sql);
			stat.setInt(1, id);
			rs = stat.executeQuery();
			while(rs.next()){
				Favc f = new Favc();
				f.setId(rs.getInt("id"));
				f.setFavcName(rs.getString("favcname"));
				list.add(f);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(con, stat, rs);
			
		}
		return list;
	}

	public int insertOne(Integer cId, int fId) {
		int count=0;
		Connection con = null;
		PreparedStatement stat = null;
		
		try {
		con  = DBUtil.createConnection();
		String sql = "insert into customer_favc(customer_id,favc_id) values(?,?)";
		stat = con.prepareStatement(sql);
		stat.setInt(1, cId);
		stat.setInt(2, fId);
		count = stat.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBUtil.close(con, stat, null);
			
		}
		return count;
	}

	public int remove(Integer cId) {
		int count=-1;
		Connection con = null;
		PreparedStatement stat = null;
		
		try {
		con  = DBUtil.createConnection();
		String sql = "delete from customer_favc where customer_id=?";
		stat = con.prepareStatement(sql);
		stat.setInt(1, cId);
		count = stat.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(con, stat, null);
			
		}
		return count;
	}

}
